package com.yangye.niodemo.rpc.server;

import com.yangye.niodemo.rpc.transport.ServerDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author yangye
 * @date 2020/12/29
 */
public class RpcServer {

	public int port;

	public RpcServer(int port) {
		this.port = port;
	}

	public void start() {
		NioEventLoopGroup boss = new NioEventLoopGroup();
		NioEventLoopGroup worker = new NioEventLoopGroup(20);
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(boss, worker)
					.channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<NioSocketChannel>() {
						@Override
						protected void initChannel(NioSocketChannel channel) throws Exception {
							System.out.println("server accept client port: " + channel.remoteAddress().getPort());
							ChannelPipeline pipeline = channel.pipeline();
							pipeline.addLast(new ServerDecoder());
							pipeline.addLast(new ServerHandler());
						}
					});
			ChannelFuture bind = b.bind(port);
			bind.sync();
			System.out.println("服务启动成功...");
			bind.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
}
